package com.ling.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ling.bean.*;
import com.ling.service.*;
import com.ling.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;

@Controller
public class QuestionController {
    private final AreaService areaService;
    private final QuestionService questionService;
    private final AnswerService answerService;
    private final UserService userService;
    private final ReportService reportService;
    private final UserMessageService userMessageService;

    private final UserTrackService userTrackService;

    @Autowired
    public QuestionController(QuestionService questionService, AnswerService answerService, UserService userService, ReportService reportService, AreaService areaService, UserMessageService userMessageService, UserTrackService userTrackService) {
        this.questionService = questionService;
        this.answerService = answerService;
        this.userService = userService;
        this.reportService = reportService;
        this.areaService = areaService;
        this.userMessageService = userMessageService;
        this.userTrackService = userTrackService;
    }

    @GetMapping("/jreble")
    @ResponseBody
    public String jreble() {
        return "see if jreble is still working";
    }

    @RequestMapping(value = "/question-home", method = RequestMethod.GET)
    public String goToHomePage() {
        return "question-home";
    }

    @RequestMapping(value = "/question/{questionId}", method = RequestMethod.GET)
    public String goToQuestion(@PathVariable String questionId, ModelMap modelMap,HttpSession httpSession) {
        Question userQuestionById = questionService.getUserQuestionById(questionId);
        if (userQuestionById == null) {
            return "redirect:/home";
        }
        modelMap.addAttribute("question", userQuestionById);

        User user = (User) httpSession.getAttribute("user");
        if (user != null) {
            //增加浏览记录
            UserTrack userTrack = new UserTrack();
            userTrack.setId(StringUtil.getRandomString(16));
            userTrack.setUserid(user.getId());
            userTrack.setTypeid(questionId);
            userTrack.setReadtime(new Date());
            //true为文章，false为问题
            userTrack.setType(false);
            userTrack.setTitle(userQuestionById.getQuestiontitle());
            userTrackService.saveUserTrack(userTrack);
        }
        return "question-view";
    }

    @RequestMapping(value = "/question/{questionId}/answer/{answerId}", method = RequestMethod.GET)
    public String goToQuestionWithAnswer(@PathVariable String questionId,@PathVariable String answerId, ModelMap modelMap,HttpSession httpSession) {
        Question userQuestionById = questionService.getUserQuestionById(questionId);
        if (userQuestionById == null) {
            return "redirect:/home";
        }
        modelMap.addAttribute("question", userQuestionById);
        Answer answer = answerService.getAnswerById(answerId);
        answer.setUser(userService.getUserById(answer.getUserid()));
        modelMap.addAttribute("answer",answer);

        User user = (User) httpSession.getAttribute("user");
        if (user != null) {
            //增加浏览记录
            UserTrack userTrack = new UserTrack();
            userTrack.setId(StringUtil.getRandomString(16));
            userTrack.setUserid(user.getId());
            userTrack.setTypeid(questionId);
            userTrack.setReadtime(new Date());
            //true为文章，false为问题
            userTrack.setType(false);
            userTrack.setTitle(userQuestionById.getQuestiontitle());
            userTrackService.saveUserTrack(userTrack);
        }
        return "question-view";
    }

    @RequestMapping(value = "/report/question/{questionId}", method = RequestMethod.GET)
    @ResponseBody
    public Msg reportQuestion(HttpSession session, @PathVariable String questionId) {
        //判断登录
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return Msg.fail().add("error","请先登录！");
        }
        Report report = new Report();
        report.setId(StringUtil.getRandomString(16));
        report.setHasread(0);
        report.setReportfieldid(questionId);
        report.setReporttype(2);
        report.setUserid(user.getId());
        //判断是否存在记录
        if (reportService.existReport(report)) {
            return Msg.fail().add("error","您已举报该问题，请不要重复操作！");
        }
        reportService.saveReport(report);

        Question question_db = questionService.getUserQuestionById(questionId);

        UserMessage userMessage = new UserMessage();
        userMessage.setEdittime(new Date());
        userMessage.setFromuserid(user.getId());
        userMessage.setFromusername(user.getNickname());
        userMessage.setHasread(0);
        userMessage.setId(StringUtil.getRandomString(16));
        userMessage.setMessagecontent("举报了你发布的问题@ " + question_db.getQuestiontitle()+"。");
        userMessage.setMessagetype(3);
        userMessage.setMessagetypeid(questionId);
        //谁发布的问题
        userMessage.setUserid(question_db.getUserid());
        userMessageService.saveUserMessage(userMessage);
        return Msg.success();
    }

    @GetMapping("/question-area/{areaId}")
    public String goToQuestionArea(@PathVariable String areaId,ModelMap map) {
        map.addAttribute("area", areaService.getArea(areaId));
        return "question-area";
    }

    //获取指定领域的所有问题
    @GetMapping(value = "/getAllQuestionsByAreaId/{areaId}/{pn}")
    @ResponseBody
    public Msg getAllQuestionsByAreaId(@PathVariable String areaId ,@PathVariable Integer pn) {
        PageHelper.startPage(pn, 15);
        List<Question> questionList = questionService.getAllQuestionsByAreaId(areaId);
        PageInfo<Question> pageInfo = new PageInfo<>(questionList);
        return Msg.success().add("pageInfo",pageInfo);
    }


    @GetMapping("/answer/{answerId}")
    public String goToViewAnswer(@PathVariable String answerId, ModelMap modelMap) {
        Answer answerById = answerService.getAnswerById(answerId);

        Question userQuestionById = questionService.getUserQuestionById(answerById.getQuestionid());
        if (userQuestionById == null) {
            return "redirect:/home";
        }
        modelMap.addAttribute("question", userQuestionById);
        answerById.setUser(userService.getUserById(answerById.getUserid()));
        modelMap.addAttribute("answer",answerById);
        return "question-view";
    }
}
